package localizer.main;

 
import java.util.Calendar;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class ServiceBroadcastReciever extends BroadcastReceiver {

	// Restart service every 30 seconds
	public static long REPEAT_TIME = 1000 * 20;
	public static long REPEAT_TIME2 = 1000 * 60 * 5;
	Config config;
	
	@Override
	public void onReceive(Context context, Intent intent) {
		config = Config.getInstance(context.getApplicationContext());
		//ConnectivityManager cm =        (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); 
		//NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
		//boolean isConnected  =  ((activeNetwork != null) && activeNetwork.isConnectedOrConnecting());
		//<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
		if( config.hasUser(context.getApplicationContext())){
			REPEAT_TIME = Long.parseLong(config.getTimeTask(context.getApplicationContext())) * 1000;
			REPEAT_TIME2 = Long.parseLong(config.getTimeLoc(context.getApplicationContext())) * 1000 * 60;
		
		    
			AlarmManager service = (AlarmManager) context
					.getSystemService(Context.ALARM_SERVICE);
			Intent i = new Intent(context, StartService.class);
			
			PendingIntent pending = PendingIntent.getBroadcast(context, 0, i,
					PendingIntent.FLAG_CANCEL_CURRENT);
			
			Calendar cal = Calendar.getInstance();
			cal.add(Calendar.SECOND, 2);
			service.cancel(pending);
			if( config.isEnableUpdateTask(context.getApplicationContext()) )service.setInexactRepeating(AlarmManager.RTC_WAKEUP,
					cal.getTimeInMillis(), REPEAT_TIME, pending);
			
			Intent i2 = new Intent(context, StartServiceLocalization.class);
			i2.putExtra("to", "server");
			PendingIntent pending2 = PendingIntent.getBroadcast(context, 0, i2,
					PendingIntent.FLAG_CANCEL_CURRENT);
			
			Calendar cal2 = Calendar.getInstance();
			cal2.add(Calendar.SECOND, 3);
			service.cancel(pending2);
			if( config.isEnableCheckUpdateLocation(context.getApplicationContext()) )service.setInexactRepeating(AlarmManager.RTC_WAKEUP,
					cal2.getTimeInMillis(), REPEAT_TIME2, pending2);;
			service = null;
		}
		config = null;
	}
}